package com.scs.application.modules.dept.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.Matr;
import com.scs.application.modules.base.entity.MatrUnit;
import com.scs.application.modules.base.entity.PackTempletItem;
import com.scs.application.modules.base.mapper.MatrMapper;
import com.scs.application.modules.base.mapper.MatrUnitMapper;
import com.scs.application.modules.base.service.PackTempletItemService;
import com.scs.application.modules.base.util.CommonService;
import com.scs.application.modules.dept.entity.Apply;
import com.scs.application.modules.dept.entity.ApplyItem;
import com.scs.application.modules.dept.entity.Demand;
import com.scs.application.modules.dept.entity.DemandItem;
import com.scs.application.modules.dept.mapper.DemandItemMapper;
import com.scs.application.modules.dept.mapper.DemandMapper;
import com.scs.application.modules.dept.service.DemandItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 科室需求计划明细 服务实现类
 * </p>
 */
@Service
public class DemandItemServiceImpl extends BaseServiceImpl<DemandItemMapper, DemandItem> implements DemandItemService {

    @Autowired
    private DemandMapper demandMapper;
    @Autowired
    private PackTempletItemService packTempletItemService;
    @Autowired
    private MatrMapper matrMapper;
    @Autowired
    private MatrUnitMapper matrUnitMapper;

    @Override
    public boolean saveOrUpdate(DemandItem entity) {

        boolean success = super.saveOrUpdate(entity);

        String demandId = entity.getDemandId();
        updateDemandAmount(demandId, null);
        return success;
    }


    @Override
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        List<DemandItem> demandItemList = this.list(Wrappers.<DemandItem>query().in("id", idList));
        boolean success = super.removeCascadeByIds(idList);
//        删除后对应 需求池删除
        List<String> applyAutoIds = demandItemList.stream()
                .filter(demandItem -> StringUtils.isNotBlank(demandItem.getApplyAutoId()))
                .map(DemandItem::getApplyAutoId)
                .collect(Collectors.toList());
        if (applyAutoIds != null && applyAutoIds.size() > 0) {
            CommonService.updateApplyInfo(applyAutoIds, -1);
        }
        updateDemandAmount(demandItemList.get(0).getDemandId(),demandItemList);
        return success;
    }

    @Override
    public boolean removeCascadeById(Serializable id) {
        return this.removeCascadeByIds(Arrays.asList(id));
    }

    private void updateDemandAmount(String demandId, List<DemandItem> demandItemRemoveList ) {
        demandMapper.updateAmount(demandId);
    }

    private Double calcOrderPrice(String demandId) {
        return this.getObj(Wrappers.<DemandItem>query().select("sum(amount)").eq("demand_id", demandId), v -> {
            if (v == null) {
                return 0.0;
            }
            return Double.valueOf(v.toString());
        });
    }


    /**
     * @Description： 批量保存模板
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatchPackage(List<DemandItem> itemList) {
        Date now = DateUtils.now();
        final int[] addNum = {1};
        //非包装耗材
        itemList.stream().forEach(applyItem -> {
            //子网格是按照名称升序排的，此处按照ID顺序进行添加，保证显示顺序与包装选择时一致
            List<String> PackTempletMatrIds = null;

            QueryWrapper queryWrapper = Wrappers.<PackTempletItem>query().eq("pack_templet_id", applyItem.getPackTempletId()).orderByDesc("matr_name");
            if (StringUtils.isNotBlank(applyItem.getPackTempletMatrIds())) {
                PackTempletMatrIds = Arrays.asList(applyItem.getPackTempletMatrIds().split(","));
                queryWrapper.in("matr_id", PackTempletMatrIds);
            }
            List<PackTempletItem> packTempletItems = packTempletItemService.list(queryWrapper);
            if (packTempletItems != null && packTempletItems.size() > 0) {
                packTempletItems.forEach(item -> {
                    DemandItem applyItemPack = new DemandItem();
                    BeanUtils.copyProperties(item, applyItemPack);

                    Matr matr = matrMapper.selectById(item.getMatrId());
                    BusinessException.throwErrorIf(matr == null, "商品[%s]不存在，请刷新重试",item.getMatrName());
                    applyItemPack.setId(null);
                    applyItemPack.setPackageRate(item.getSkuQty() / item.getPackageQty())
                            .setSkuPrice(item.getAmount() / item.getSkuQty())
                            .setDemandId(applyItem.getDemandId());
                    this.saveOrUpdate(applyItemPack);

                    //修改时间加一秒，不然同一时间排序无法顺序排序
                    LocalDateTime dateNext = DateUtils.dateToLocalDateTime(DateUtils.addSeconds(now, addNum[0]));
                    applyItemPack.setGmtCreate(dateNext).setGmtModified(dateNext);
                    this.updateById(applyItemPack);
                    addNum[0]++;
                });
            }
        });
    }

    @Override
    public void saveBatchForPurchaseDemand(List<DemandItem> entityList) {
        Date now = DateUtils.now();
        final int[] addNum = {1};
        DemandItem demandItem = entityList.get(0);
        if (StringUtils.isBlank(demandItem.getDemandId())) {
            throw new BusinessException("主单据保存失败，请刷新浏览器重试");
        }
        Demand demand = demandMapper.selectById(demandItem.getDemandId());
        if (demand == null) {
            throw new BusinessException("主单据保存失败，请刷新浏览器重试");
        }
        List<DemandItem> addList = new ArrayList<>();
        List<String> matrIds = entityList.stream().filter(tmp -> StringUtils.isBlank(tmp.getPackTempletItemId())).map(DemandItem::getMatrId).distinct().collect(Collectors.toList());
        if (matrIds != null && matrIds.size() > 0){
            List<Matr> matrs = matrMapper.selectBatchIds(matrIds);
            List<MatrUnit> purchaseUnitMax = matrUnitMapper.getPurchaseUnitMax(Wrappers.<MatrUnit>query()
                    .in("matr_id", matrIds).eq("flag_purchase", 1)
                    .eq("flag_disabled", 0));
            Map<String, List<MatrUnit>> listMap = purchaseUnitMax.stream().collect(Collectors.groupingBy(MatrUnit::getMatrId));
            matrs.forEach(matr -> {
                DemandItem newItem = new DemandItem();
                List<MatrUnit> matrUnits = listMap.get(matr.getId());
                BeanUtils.copyProperties(matr, newItem);
                newItem.setPackageQty(1D);
                newItem.setPackageUnit(matr.getSkuUnit()).setPackageRate(1D);
                newItem.setDemandId(demand.getId());
                newItem.setMatrId(matr.getId()).setMatrName(matr.getName()).setMatrSpec(matr.getSpec()).setMatrModel(matr.getModel());
                newItem.setPackageQty(1D);
                if (matrUnits != null && matrUnits.size() > 0) {
                    MatrUnit matrUnit = matrUnits.get(0);
                    newItem.setPackageRate(matrUnit.getRate()).setPackageUnit(matrUnit.getUnit());
                }
                newItem.setSkuQty(newItem.getPackageQty() * newItem.getPackageRate());
                newItem.setAmount(newItem.getSkuQty() * newItem.getSkuPrice()).setId(null);
                newItem.setId(null);
                addList.add(newItem);
            });
        }

        List<String> getPackTempletItemIdList = entityList.stream().filter(tmp -> StringUtils.isNotBlank(tmp.getPackTempletItemId())).map(DemandItem::getPackTempletItemId).distinct().collect(Collectors.toList());
        if (getPackTempletItemIdList != null && getPackTempletItemIdList.size() > 0){
            List<PackTempletItem> packTempletItems = packTempletItemService.list(Wrappers.<PackTempletItem>query().in("id", getPackTempletItemIdList));
            if (packTempletItems != null && packTempletItems.size() > 0) {
                packTempletItems.forEach(item -> {
                    DemandItem demandItemNew = new DemandItem();
                    BeanUtils.copyProperties(item, demandItemNew);
                    demandItemNew.setId(null);
                    demandItemNew.setPackageRate(demandItemNew.getPackageQty() / demandItemNew.getSkuQty())
                            .setSkuPrice(demandItemNew.getAmount() / demandItemNew.getSkuQty())
                            .setDemandId(entityList.get(0).getDemandId());
                    addList.add(demandItemNew);
                });
            }
        }
        if (addList.size() > 0) {
            this.saveBatch(addList);
            updateDemandAmount(demandItem.getDemandId(), null);
        }
    }
}
